# 接口文档分析
import asyncio
import os
import re
import subprocess
import fire
from metagpt.actions import Action
from metagpt.logs import logger
from metagpt.roles.role import Role, RoleReactMode
from metagpt.schema import Message
from src.tools.Translated import Translated
from src.tools.extractCode import extract


def read_files_in_folder(folder_path):
    context = ""  # 初始化一个空字符串，用于保存所有文件内容
    # 遍历文件夹中的所有文件
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        if os.path.isfile(file_path):  # 确保路径指向一个文件而不是文件夹
            context += f"File: {filename}\n"
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    context += content + "\n\n" + "=" * 50 + "\n\n"  # 添加文件内容和分隔线到context中
            except Exception as e:
                context += f"Error reading {filename}: {str(e)}\n\n" + "=" * 50 + "\n\n"

    return context

# 指定要读取的文件夹路径
# folder_path = r'C:\Users\32728\Desktop\controller'  # 替换成你实际的文件夹路径

# 调用函数读取文件夹中所有文件的内容并保存到变量context中
# context = read_files_in_folder(folder_path)


class SimpleWriteCode(Action):
    PROMPT_TEMPLATE: str = """
     对{instruction}中的每个接口分析并分别生成接口文档按照以下五点要求：
    0.具体的接口描述，详细一点
    1.方法：常用的方法就是下面的四种：GET PUT POST DELETE

    2.url

    3.请求参数和返回参数：请求参数和返回参数都分为：字段、说明、类型、备注、是否必填这5列。字段：类的属性，说明：中文释义，类型：属性的类型，只有String、Number、Object、Array四大类，备注：一些解释语，或者写简单的示例

    4.返回参数，要分两种情况讨论：只返回接口调用成功或者失败：code、reason，返回参数：字段、类型
    对每个接口分别按以上要求生成一篇接口文档，详细一点，用中文回答
    Return ```python your_code_here ``` with NO other texts,
    your code:
    """

    name: str = "SimpleWriteCode"

    async def run(self, instruction: str):
        prompt = self.PROMPT_TEMPLATE.format(instruction=instruction)

        rsp = await self._aask(prompt)

        code_text = SimpleWriteCode.parse_code(rsp)

        return code_text

    @staticmethod
    def parse_code(rsp):
        pattern = r"```python(.*)```"
        match = re.search(pattern, rsp, re.DOTALL)
        code_text = match.group(1) if match else rsp
        return code_text


class SimpleRunCode(Action):
    name: str = "SimpleRunCode"

    async def run(self, code_text: str):
        result = subprocess.run(["python3", "-c", code_text], capture_output=True, text=True)
        code_result = result.stdout
        logger.info(f"{code_result=}")
        return code_result


class SimpleCoder(Role):
    name: str = "Alice"
    profile: str = "SimpleCoder"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_actions([SimpleWriteCode])

    async def _act(self) -> Message:
        logger.info(f"{self._setting}: to do {self.rc.todo}({self.rc.todo.name})")
        todo = self.rc.todo  # todo will be SimpleWriteCode()

        msg = self.get_memories(k=1)[0]  # find the most recent messages
        code_text = await todo.run(msg.content)
        msg = Message(content=code_text, role=self.profile, cause_by=type(todo))

        return msg


class RunnableCoder(Role):
    name: str = "Alice"
    profile: str = "RunnableCoder"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_actions([SimpleWriteCode])
        # self.set_actions([SimpleWriteCode, SimpleRunCode])
        self._set_react_mode(react_mode=RoleReactMode.BY_ORDER.value)

    async def _act(self) -> Message:
        logger.info(f"{self._setting}: to do {self.rc.todo}({self.rc.todo.name})")
        # By choosing the Action by order under the hood
        # todo will be first SimpleWriteCode() then SimpleRunCode()
        todo = self.rc.todo

        msg = self.get_memories(k=1)[0]  # find the most k recent messages
        result = await todo.run(msg.content)

        msg = Message(content=result, role=self.profile, cause_by=type(todo))
        self.rc.memory.add(msg)
        return msg

async def main(file_path):
    # 将路径中的"\"转换成"/"
    file_path = Translated(file_path)
    code = extract(file_path)
    # 创建 RunnableCoder 实例
    role = RunnableCoder()

    # 记录输入的消息
    logger.info(code)

    # 异步运行 run 方法，并等待结果
    resdata = await role.run(code)

    return resdata


def controller_anakysis_main(file_path):
    data = asyncio.run(main(file_path))
    print("12222222231312334245435435")
    print(data)
    return data


if __name__ == '__main__':
    file_path = r"../../java/project/backend/src/main/java/com/open/harmony/controller/OrderController.java"
    controller_anakysis_main(file_path)
